import 'package:fluent_ui/fluent_ui.dart';

import '../../api/school_student_api.dart';
import '../../components/data_table.dart';
import '../../model/school_student.dart';
import '../../utils/loading_utils.dart';
import '../app/app_dict_data.dart';

abstract class SchoolStudentField {}

///学校学生-查询字段
enum SchoolStudentQueryField implements SchoolStudentField {
  name('学号/姓名'),
  enterYear('入学年份'),
  status("状态");

  final String label;

  const SchoolStudentQueryField(this.label);
}

///学校学生-输入字段
enum SchoolStudentInputField implements SchoolStudentField {
  code('学号', checked: true),
  name('姓名', checked: true),
  enterYear('入学年份', checked: true),
  remark('备注'),
  status("状态", isAdd: false);

  final String label;
  final bool checked, isAdd;

  const SchoolStudentInputField(
    this.label, {
    this.checked = false,
    this.isAdd = true,
  });

  String? validHandler<T>(final T? val) {
    if (checked) {
      if (val == null) {
        return '$label不能为空';
      }
      if (val is String) {
        return val.isEmpty ? '$label不能为空' : null;
      }
      if (val is List) {
        return val.isEmpty ? '$label不能为空' : null;
      }
    }
    return null;
  }
}

//学校学生-视图模型
class SchoolStudentViewModel extends ChangeNotifier {
  //查询字段
  final _queryFields = <SchoolStudentQueryField, TextEditingController>{
    for (var field in SchoolStudentQueryField.values)
      field: TextEditingController()
  };

  //输入字段
  final _inputFields = <SchoolStudentInputField, TextEditingController>{
    for (var field in SchoolStudentInputField.values)
      field: TextEditingController()
  };

  ///获取控制器
  TextEditingController? getController<T extends SchoolStudentField>(T field) {
    //查询字段
    if (field is SchoolStudentQueryField) {
      return _queryFields[field];
    }
    //输入字段
    if (field is SchoolStudentInputField) {
      return _inputFields[field];
    }
    return null;
  }

  ///获取字段值
  String? getFieldValue<T extends SchoolStudentField>(final T field) {
    final ctr = getController(field);
    if (ctr != null) {
      return ctr.text;
    }
    return null;
  }

  ///设置字段值
  void setFieldValue<T extends SchoolStudentField>(T field, String? val) {
    final controller = getController(field);
    if (controller != null) {
      controller.text = val ?? '';
    }
  }

  final _statusOpts = <ComboBoxItem<String>>[];

  ///获取状态选项集合
  List<ComboBoxItem<String>> get statusOpts => _statusOpts;

  ///加载字典
  void _loadDict(final List<Future<dynamic>> futures) {
    //状态
    if (_statusOpts.isEmpty) {
      final future = appDictData.buildOpts('status').then((opts) {
        if (opts.isNotEmpty) {
          _statusOpts.addAll(opts);
        }
      });
      futures.add(future);
    }
  }

  ///加载初始化
  void loadInit({final VoidCallback? afterHandler}) async {
    final futures = <Future<dynamic>>[];
    //加载字典
    _loadDict(futures);
    //请求等待
    if (futures.isNotEmpty) {
      await Future.wait(futures);
      notifyListeners();
    }
    //回调处理
    if (afterHandler != null) {
      afterHandler.call();
    }
  }

  ///清空查询字段
  void cleanQueryFields() {
    for (var ctl in _queryFields.values) {
      ctl.clear();
    }
  }

  ///清空输入字端
  void cleanInputFields() {
    for (var ctl in _inputFields.values) {
      ctl.clear();
    }
  }

  ///分页查询模型
  final queryModel = PageModel<SchoolStudentItemRes>();

  ///分页查询
  void query(final String schoolId) async {
    try {
      loading.showLoading();
      final enterYear = getFieldValue(SchoolStudentQueryField.enterYear);
      final status = getFieldValue(SchoolStudentQueryField.status);
      final req = SchoolStudentQueryReq(
        schoolId: schoolId,
        name: getFieldValue(SchoolStudentQueryField.name) ?? '',
        enterYear: int.tryParse(enterYear ?? '') ?? 0,
        status: int.tryParse(status ?? '') ?? -1,
        index: queryModel.current,
        size: queryModel.size,
      );
      final res = await schoolStudentApi.query(req);
      if (res.isSuccessed) {
        queryModel.buildResData(res);
      }
      debugPrint('schoolStudentApi.query(req:${req.toMap()})=>$res');
    } finally {
      loading.dismiss();
    }
  }

  ///加载数据
  void getInfoById(final String id) async {
    try {
      loading.showLoading();
      //加载数据
      final res = await schoolStudentApi.info(id);
      if (res.isSuccessed) {
        setFieldValue(SchoolStudentInputField.code, res.code);
        setFieldValue(SchoolStudentInputField.name, res.name);
        setFieldValue(SchoolStudentInputField.remark, res.remark);
        setFieldValue(SchoolStudentInputField.enterYear, '${res.enterYear}');
        setFieldValue(SchoolStudentInputField.status, '${res.status}');
        //触发通知
        notifyListeners();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///新增
  void onAddHandler(final String schoolId, final VoidCallback handler) async {
    try {
      loading.showLoading();
      final enterYear = getFieldValue(SchoolStudentInputField.enterYear);
      final req = SchoolStudentAddReq(
        schoolId: schoolId,
        code: getFieldValue(SchoolStudentInputField.code) ?? '',
        name: getFieldValue(SchoolStudentInputField.name) ?? '',
        remark: getFieldValue(SchoolStudentInputField.remark) ?? '',
        enterYear: int.tryParse(enterYear ?? '') ?? 0,
      );
      final res = await schoolStudentApi.add(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///修改处理
  void onModifyHandler(final String id, final VoidCallback handler) async {
    try {
      loading.showLoading();
      final enterYear = getFieldValue(SchoolStudentInputField.enterYear);
      final status = getFieldValue(SchoolStudentInputField.status);
      final req = SchoolStudentModifyReq(
        id: id,
        code: getFieldValue(SchoolStudentInputField.code) ?? '',
        name: getFieldValue(SchoolStudentInputField.name) ?? '',
        remark: getFieldValue(SchoolStudentInputField.remark) ?? '',
        enterYear: int.tryParse(enterYear ?? '') ?? 0,
        status: int.tryParse(status ?? '') ?? 1,
      );
      final res = await schoolStudentApi.modify(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///删除处理
  void onDeleteHandler({required String schoolId, id}) async {
    try {
      loading.showLoading();
      //删除
      final res = await schoolStudentApi.delete(id);
      if (res.isSuccessed) {
        query(schoolId);
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
